import Vue from 'vue'
import VueRouter from 'vue-router'

import utils from "@/config/utils";

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'Home',
    component: () => import('../views/Home.vue')
  },
  {
    path: '/form',
    name: 'Form',
    component: () => import('../views/Form.vue'),
    meta: {
      requireAuth: true
    },
  },
  {
    path: "/form/createForm",
    name: "CreateForm",
    component: () => import('../views/CreateForm.vue'),
    meta: {
      requireAuth: true
    }
  },
  {
    path: "/form/formView",
    name: "FormView",
    component: () => import('../views/FormView.vue'),
    meta: {
      requireAuth: true
    }
  },
  {
    path: "/form/formItem/:id",
    name: "FormItem",
    component: () => import('../views/FormItem.vue'),
    meta: {
      requireAuth: true
    }
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue')
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('../views/Register.vue')
  },
  {
    path: '/forgetpwd',
    name: 'Forgetpwd',
    component: () => import('../views/Forgetpwd.vue')
  },
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach((to, from, next) => {
  // 修改标题
  if (to.meta.title) {
    document.title = to.meta.title
  } else {
    document.title = '表单大师'
  }
  //console.log(to)
  if (to.matched.some(res => res.meta.requireAuth)) { // 判断是否需要登录权限
    //console.log(from);
    if (utils.getUserId()) { // 判断是否登录
      next();
    } else { // 没登录则跳转到登录界面
      if (to.path === "/login") {
        next()
      } else {
        next({
          path: "/login",
          query: {
            redirect: to.fullPath
          } //将目的路由地址存入login的query中
        })
      }
    }
  } else {
    next();
  }
})

export default router;
